<?php

namespace Framework\Foundation\Entity;

use App\Foundation\Utils\StringUtil;
use Framework\Foundation\Database\FDB;
use think\facade\Db;

trait EntityExpand
{
    /**
     * @param $field
     * @param $value
     * @return null|static
     * @throws \Envms\FluentPDO\Exception
     */
    public static function getByAttr($field, $value)
    {
        $className = get_called_class();
        $name = StringUtil::getNameBySpaceName($className);
        $tableName = StringUtil::convertObjectToTable(str_replace('Entity', '', $name));

        $ret = FDB::connection(self::$connection)->from($tableName)->where($field, $value)->limit(1)->fetch();
        if (empty($ret)) {
            return null;
        }
        return new $className($ret);
    }

    /**
     * @param $value
     * @return static|null
     * @throws \Envms\FluentPDO\Exception
     */
    public static function getByPk($value)
    {
        $className = get_called_class();
        $name = StringUtil::getNameBySpaceName($className);
        $tableName = StringUtil::convertObjectToTable(str_replace('Entity', '', $name));

        $field = $tableName . '_id';
        return self::getByAttr($field, $value);
    }

    public static function updateByAttr($field, $condition, $data)
    {
        $className = get_called_class();
        $name = StringUtil::getNameBySpaceName($className);
        $tableName = StringUtil::convertObjectToTable(str_replace('Entity', '', $name));

        return FDB::connection(self::$connection)->update($tableName)->where(
            $field,
            $condition
        )->set($data)->execute();
    }

    public static function insert(array $value)
    {
        $className = get_called_class();
        $name = StringUtil::getNameBySpaceName($className);
        $tableName = StringUtil::convertObjectToTable(str_replace('Entity', '', $name));

        $query = FDB::connection(self::$connection)->insertInto($tableName)->values($value);
        $ret = $query->execute();
        return $ret;
    }

    public static function deleteByAttr($field, $value)
    {
        $className = get_called_class();
        $name = StringUtil::getNameBySpaceName($className);
        $tableName = StringUtil::convertObjectToTable(str_replace('Entity', '', $name));

        return FDB::connection(self::$connection)->update($tableName)->set([
            'is_deleted' => 1,
            'deleted_at' => date('Y-m-d H:i:s')
        ])->where($field, $value)->execute();
    }

    public static function deleteByPk($value)
    {
        $className = get_called_class();
        $name = StringUtil::getNameBySpaceName($className);
        $tableName = StringUtil::convertObjectToTable(str_replace('Entity', '', $name));

        return self::deleteByAttr($tableName . '_id', $value);
    }
}
